package com.java2108.hetong.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.itext.pdf.service.PdfService;
import com.bw.zhanggm.common.AjaxResult;
import com.java2108.hetong.entity.HtCategorie;
import com.java2108.hetong.entity.HtContract;
import com.java2108.hetong.entity.HtType;
import com.java2108.hetong.entity.HtTypeRelation;
import com.java2108.hetong.service.IHtCategorieService;
import com.java2108.hetong.service.IHtContractService;
import com.java2108.hetong.service.IHtTypeRelationService;
import com.java2108.hetong.service.IHtTypeService;
import com.java2108.hetong.vo.ContractDetailVo;
import com.java2108.hetong.vo.ContractVo;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 合同信息表 前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-02-23
 */
@RestController
@RequestMapping("/hetong/")
public class HtContractController {

    @Autowired
    IHtContractService iHtContractService;


    @Autowired
    private PdfService pdfService;

    @Autowired
    HttpServletResponse response;


    @GetMapping("pdfDetail")
    public void pdfDetail(String id) throws IOException {
        HtContract htContract = iHtContractService.getById(id);
        String pdfName = "hetong" + htContract.getId()+".pdf";
        pdfService.export(Arrays.asList(htContract), pdfName, htContract.getName(), HtContract.class);
        pdfService.preview(pdfName,response);
    }

    @GetMapping("pdf")
    public AjaxResult pdf() throws IOException, NoSuchFieldException, IllegalAccessException {
        List<HtContract> list = iHtContractService.list();
        //生成文件
        pdfService.export(list, "hetong.pdf","合同列表", HtContract.class);
        //签章，给pdf文件添加签章
        pdfService.sign("hetong.pdf","hetong-sign.pdf");
        //预览生成的文件
        pdfService.preview("hetong-sign.pdf",response);
//        pdfService.download("hetong.pdf",response);

        /*Field id = HtContract.class.getDeclaredField("id");
        final Object o = id.get(list.get(0));
        HtContract htContract = HtContract.class.newInstance();
        Method[] methods = HtContract.class.getMethods();
        Object invoke = methods[0].invoke(list.get(0));
        list.get(0).getName();*/

        return AjaxResult.success();
    }



    @GetMapping("getContractId")
    public AjaxResult getContractId() {
        Snowflake snowflake = IdUtil.getSnowflake();
        return AjaxResult.success(snowflake.nextIdStr());
    }


    /**
     * 列表接口
     * @param contract
     * @param page
     * @return
     */
    @GetMapping("page")
    public AjaxResult page(HtContract contract, Page page) {
        LambdaQueryWrapper<HtContract> queryWrapper = new LambdaQueryWrapper<>();
        if (contract.getName() != null) {
            queryWrapper.like(HtContract::getName, contract.getName());
        }
        queryWrapper.ge(contract.getDateStart()!=null, HtContract::getDate, contract.getDate());
        queryWrapper.lt(contract.getDateEnd()!=null, HtContract::getDate, contract.getDate());
        //设置查询条件
        Page<HtContract> pageInfo = iHtContractService.page(page, queryWrapper);

        List<HtContract> records = pageInfo.getRecords();
        Set<Integer> cateSet = records.stream().map(item -> item.getCategoryId()).collect(Collectors.toSet());
        List<HtCategorie> HtCategorieList = iHtCategorieService.listByIds(cateSet);
        Map<Integer, String> HtCategorieMap = HtCategorieList.stream().collect(Collectors.toMap(HtCategorie::getId, HtCategorie::getName));

        records.forEach(ht->{
            ht.setCategoryName(HtCategorieMap.get(ht.getCategoryId()));
            /*htContractList.forEach(cate->{
                if (cate.getId().equals(ht.getCategoryId())) {
                    ht.setCategoryName(cate.getCategoryName());
                }
            });*/
//            HtCategorie categorieService = iHtCategorieService.getById(ht.getCategoryId());

        });

        return AjaxResult.success(pageInfo);
    }


    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IHtTypeService typeService;

    @Autowired
    private IHtTypeRelationService typeRelationService;

    @Autowired
    private IHtCategorieService iHtCategorieService;


    /**
     * 新增和修改是一个接口
     * @param contract
     * @return
     */
    @PostMapping("save")
    public AjaxResult save(@RequestBody HtContract contract) {
        //保存主表
        iHtContractService.saveOrUpdate(contract);
        //删除关系表的数据
        LambdaQueryWrapper<HtTypeRelation> deleteQuery = new LambdaQueryWrapper<>();
        deleteQuery.eq(HtTypeRelation::getHtId, contract.getId());
        typeRelationService.remove(deleteQuery);
        //保存类型的关系表
        List<Integer> typeIdList = contract.getTypeIdList();
        List<HtTypeRelation> htTypeRelationList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(typeIdList)) {
            typeIdList.forEach(item->{
                HtTypeRelation htTypeRelation = new HtTypeRelation().setHtId(contract.getId()).setTypeId(item);
                htTypeRelationList.add(htTypeRelation);
            });
            typeRelationService.saveBatch(htTypeRelationList);
        }
        //定义流程变量，如果流程图，直接写成zhangsan、lisi之类的，就不需要写variables
        Map<String, Object> variables = new HashMap<>();
        variables.put("caiwu", "zhangsan");
        variables.put("fawu", "lisi");
        //提交到工作流
        runtimeService.startProcessInstanceById("hetong", contract.getId()+"", variables);
        return AjaxResult.success();
    }

    /**
     * 新增或回显是一个接口
     * @param id
     * @return
     */
    public AjaxResult hetongInit(Long id) {
        //返回结果
        ContractVo contractVo = new ContractVo();
        if (id != null && id > 0) {
            HtContract htContract = iHtContractService.getById(id);
            //拷贝对象属性
            BeanUtil.copyProperties(htContract, contractVo,true);
            //处理分类
            Integer categoryId = htContract.getCategoryId();
            HtCategorie categorie2 = iHtCategorieService.getByParentId(categoryId);
            HtCategorie categorie1 = iHtCategorieService.getByParentId(categorie2.getId());

            List<HtCategorie> categoryList = iHtCategorieService.getListById(categorie2.getId());
            List<HtCategorie> category2List = iHtCategorieService.getListById(categorie1.getId());
            List<HtCategorie> category1List = iHtCategorieService.getListById(null);

            contractVo.setCategory2Id(categorie2.getId());
            contractVo.setCategory1Id(categorie1.getId());
            contractVo.setCategory1IdList(categoryList);
            contractVo.setCategory2IdList(category2List);
            contractVo.setCategory3IdList(categoryList);
        }
        //查询type所有数据
        List<HtType> typeList = typeService.list();
        contractVo.setTypeList(typeList);

        return AjaxResult.success(contractVo);
        
    }


    /**
     * 详情接口
     * @param id
     * @return
     */
    @GetMapping("getDetail")
    public AjaxResult getDetail(Long id) {
        //定义返回结果
        ContractDetailVo contractDetailVo = new ContractDetailVo();
        //查询合同信息
        HtContract htContract = iHtContractService.getById(id);

        //查询分类名称
        Integer categoryId = htContract.getCategoryId();
        HtCategorie categorie3 = iHtCategorieService.getById(categoryId);
        HtCategorie categorie2 = iHtCategorieService.getByParentId(categoryId);
        HtCategorie categorie1 = iHtCategorieService.getByParentId(categorie2.getId());

        contractDetailVo.setCategory1Name(categorie1.getName());
        contractDetailVo.setCategory2Name(categorie2.getName());
        contractDetailVo.setCategory3Name(categorie3.getName());
        //查询类型
        QueryWrapper<HtTypeRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ht_id", id);
        List<HtTypeRelation> htTypeRelationList = typeRelationService.list(queryWrapper);

        List<Integer> typeIds = htTypeRelationList.stream().map(item -> item.getTypeId()).collect(Collectors.toList());
        List<HtType> typeList = typeService.listByIds(typeIds);
        contractDetailVo.setTypeList(typeList);

        return AjaxResult.success(contractDetailVo);

    }





}
